package com.hs.framework.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * 文件
 */
public class FileUtils {

    private static String getRootPath() {
        ///storage/emulated/0
        File storageDir = Environment.getExternalStorageDirectory();
        try {
            if (storageDir != null) {
                String path = storageDir.getAbsolutePath();
                if (!TextUtils.isEmpty(path)) {
                    File dir = new File(path +"/hs");
                    if (!dir.exists()) {
                       boolean flag =  dir.mkdirs();
                       Log.d("getRootPath",flag+"");
                    }
                    return dir.getPath();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }



//    String dbFileName = "charge.db";
//    String path = MyApplication.getApp().getCabinetStoragePath();
//            if (StringUtils.isNotEmpty(path)){
//        if (!path.endsWith("/")){
//            path = path + "/";
//        }
//        dbFileName = path + dbFileName;
//    }
    /**
     *  创建文件
     * @param dbName
     * @return
     */
    public static String createDbRootPath(String dbName){
       String rootFile = getRootPath();
        try {
            if (!TextUtils.isEmpty(rootFile)) {
                File dir = new File(rootFile , dbName);
                if (!dir.exists()) {
                   boolean flag = dir.mkdirs();
                   Log.d("createDbRootPath",flag+"");
                }
                return dir.getPath();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
       return "";
    }

    public static void writeFile(String strFilePath,String strcontent) {
        // 每次写入时，都换行写
        String strContent = strcontent;// + "\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(strContent.getBytes("utf-8"));
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File.");
        }
    }



}
